// pages/wine/wine.js
const app = getApp()
var api = require('../../utils/api.js')
var util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    limit: 30,
    page: 1,
    total_page: 0,
    wineList: [], //列表
    hasMore: true,
    wineDome: true,  //酒柜弹窗控制
    numbers: 1,
    buyGoods: [], //购买商品信息 
    fadeInText:true,  //蒙层控制
    fadeInTextHops:true,  //酒花弹窗控制
    fadeInMarryText: true,  //合成成功弹窗控制
    lastTime:0,
    listType:1,
    codeCol: false
  },
  toTop: function () {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 10
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function (options) {
    this.toTop();
    if (app.globalData.sku_code){
      var sku_code = app.globalData.sku_code
    }else{
      var sku_code=''
    }
    if (app.globalData.winType){
      this.setData({
        listType: app.globalData.winType
      })
    }

    //是否第一次登录小程序
    if (app.globalData.accountInfo.first_flag==1){
      this.setData({
        first_flag: true
      })
    }else{
      this.setData({
        first_flag: false
      })
    }


    wx.hideShareMenu() // 隐藏分享按钮
    this.setData({
      wineList: [],
      page: 1,
      total_page: 0,
      wineDome: true,
      sku_code:sku_code,
      wine_guide: app.globalData.base_url +'images/wine_guide.png',
      wine_blank: app.globalData.base_url + 'images/wine_blank.png'
    })
    this.wineList();
    this.hopsList();
  },
  winTypeSel:function(e){
    this.toTop();
    this.outSelect();
    this.outSelectHops();
    this.setData({
      listType: e.currentTarget.dataset.type,
      sku_code:""
    })
    app.globalData.winType = e.currentTarget.dataset.type
  },
  winTypeSelTo: function (e) {
    this.outSelect();
    this.outSelectHops();
    this.setData({
      listType: e.currentTarget.dataset.type,
      sku_code: e.currentTarget.dataset.code
    })
    app.globalData.winType = e.currentTarget.dataset.type
  },
  // 淡入
  fadeIn:function(){
    var that = this;
    var fadeIn = wx.createAnimation({
      duration: 500
    })
    that.setData({
      fadeInText: false
    })
    fadeIn.opacity(1).step();
    that.setData({
      animationData: fadeIn.export()
    })
  },
  // 淡出
  fadeOut:function(){
    var that =this;
    var fadeOut = wx.createAnimation({
      duration: 500
    })
    fadeOut.opacity(0).step();
    that.setData({
      animationData: fadeOut.export()
    })
    let timer = setTimeout(function () {
      that.setData({
        fadeInText: true
      })
      clearTimeout(timer);
    }, 500)
  },
  // 飞入
  flyInto:function(){
    var that = this;
    var flyInto = wx.createAnimation({
      duration: 300
    })
    flyInto.bottom("20rpx").step();
    that.setData({
      flyIntoData: flyInto.export()
    })
  },
  // 飞出
  flyOut:function(){
    var that = this;
    var flyOut = wx.createAnimation({
      duration: 300
    })
    flyOut.bottom('-400rpx').step();
    that.setData({
      flyIntoData: flyOut.export()
    })
  },

  // 酒花淡入
  fadeInHops: function () {
    var that = this;
    var fadeInHops = wx.createAnimation({
      duration: 500
    })
    that.setData({
      fadeInTextHops: false
    })
    fadeInHops.opacity(1).step();
    that.setData({
      animationDataHops: fadeInHops.export()
    })
  },
  // 酒花淡出
  fadeOutHops: function () {
    var that = this;
    var fadeOutHops = wx.createAnimation({
      duration: 500
    })
    fadeOutHops.opacity(0).step();
    that.setData({
      animationDataHops: fadeOutHops.export()
    })
    let timer = setTimeout(function () {
      that.setData({
        fadeInTextHops: true
      })
      clearTimeout(timer);
    }, 500)
  },
  // 酒花飞入
  flyIntoHops: function () {
    var that = this;
    var flyIntoHops = wx.createAnimation({
      duration: 300
    })
    flyIntoHops.bottom("20rpx").step();
    that.setData({
      flyIntoDataHops: flyIntoHops.export()
    })
  },
  // 酒花飞出
  flyOutHops: function () {
    var that = this;
    var flyOutHops = wx.createAnimation({
      duration: 300
    })
    flyOutHops.bottom('-400rpx').step();
    that.setData({
      flyIntoDataHops: flyOutHops.export()
    })
  },

  // 合成淡入
  fadeInMarry: function () {
    var that = this;
    var fadeInMarry = wx.createAnimation({
      duration: 500
    })
    that.setData({
      fadeInMarryText: false
    })
    fadeInMarry.opacity(1).step();
    that.setData({
      animationData: fadeInMarry.export()
    })
  },
  // 合成淡出
  fadeOutMarry: function () {
    var that = this;
    var fadeOutMarry = wx.createAnimation({
      duration: 500
    })
    fadeOutMarry.opacity(0).step();
    that.setData({
      animationData: fadeOutMarry.export()
    })
    let timer = setTimeout(function () {
      that.setData({
        fadeInMarryText: true
      })
      clearTimeout(timer);
    }, 500)
  },


  // 显示酒花操作按钮
  intoSelectHops: function (e) {
    var that = this;
    this.setData({
      goodsInfoHops: e.currentTarget.dataset.goodsInfo
    })
    var id = this.data.goodsInfoHops.id;
    api.POST({
      params: { id: id },
      url: app.globalData.base_url + 'hops/createLog',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          // console.log()
          that.setData({
            linkCode: res.data.data.result.linkCode
          })
          that.fadeInHops();
          that.flyIntoHops();
        } else {
          util.showError(res.data.code);
        }
      },
      fail: function (fail) {
        util.showError("登录失败，请检查网络");
      }
    })

  },
//关闭引导页
  guidePageCol:function(){
    this.setData({
      first_flag:false
    })
    app.globalData.accountInfo.first_flag=2;
  },

  // 隐藏操作按钮
  outSelectHops: function () {
    this.flyOutHops();
    this.fadeOutHops();
    this.fadeOutMarry();
  },

// 显示酒柜操作按钮
intoSelect:function(e){
  var that = this
  this.setData({
    goodsInfo:e.currentTarget.dataset.goodsInfo
  })
  that.fadeIn();
  that.flyInto();
},
// 隐藏酒花操作按钮
outSelect:function(){
  this.flyOut();
  this.fadeOut();
},
  onHide:function(){
    app.globalData.sku_code='';
    this.outSelect();
  },

  //页面下拉刷新
  onPullDownRefresh: function () {
    var that = this;
    setTimeout(function () {
      that.resetData()
    }, 1000)
  },
  //刷新页面
  resetData: function () {
    var that = this
    that.setData({
      page: 1,
      // hasMore: true
    });
    that.wineList();
  },

  //页面上拉触底
  onReachBottom: function (e) {
    this.loadMore();
  },

  //加载更多
  loadMore: function () {
    // console.log("到底啦！")
    if (this.data.page >= this.data.total_page) {
      return;
    }
    wx.showLoading({
      title: '加载中',
    })
    this.setData({
      page: this.data.page + 1
    });
    this.wineList();
  },

  // 酒花列表获取
  hopsList:function(){
    var that = this;
    api.POST({
      params: {
      },
      url: app.globalData.base_url + 'hops/mylist',
      success: function (res) {
        wx.hideLoading()
        if (util.isEmpty(res.data.code)) {
          var hopsList = res.data.data.result
          hopsList.forEach(function(item){
            // console.log(item)
            item.percent = ((item.num / item.use_num)*100).toFixed(0)
          })
          // console.log(hopsList)
          var data = res.data.data.result
          that.split_array(data,3,"hops")
          // that.setData({
          //   hopsList: res.data.data.result
          // });

        } else {
          util.showError(res.data.code);
        }
      },
      fail: function (fail) {
        util.showError("登录失败，请检查网络");
      }
    })
  },

  //酒柜列表
  wineList: function () {
    var that = this;
    api.POST({
      params: {
        page: that.data.page,
        limit: that.data.limit
      },
      url: app.globalData.base_url + 'winecabinet/index',
      success: function (res) {
        wx.hideLoading()
        if (util.isEmpty(res.data.code)) {
          var paging = res.data.data.paging;
          var totalPage = paging.total_page;
          var currentPage = paging.page;
          var count = paging.count;
          var resultList = res.data.data.list;
          if (currentPage == 1) {
            var itemData = resultList;
          } else {
            var itemData = that.data.wineList.concat(resultList);
          }
          that.split_array(itemData,3,"winBox");
          that.setData({
            hasMore: (currentPage >= totalPage) ? false : true,
            total_page: totalPage,
            wineList: itemData
          });

        } else {
          util.showError(res.data.code);
        }
        wx.stopPullDownRefresh();
      },
      fail: function (fail) {
        wx.hideLoading()
        util.showError("登录失败，请检查网络");
      }
    })
  },

  // 已购买商品详情
  goodsInfo: function (e) {
    var goodsInfo =this.data.goodsInfo;
    wx.navigateTo({
      url: '../wineSelfGet/wineSelfGet?sku_code=' + goodsInfo.sku_code
    })
  },
// 
  //立即购买
  buyNow: function (e) {
    // console.log("立即购买")
    var that = this;
    var goodsInfo = that.data.goodsInfo;
    var sku_code = goodsInfo.sku_code;
    var curTime = e.timeStamp;
    var lastTime = this.data.lastTime;
    this.setData({
      lastTime: curTime
    })
    if (lastTime > 0) {
      if (curTime - lastTime < 500) {
        return false;
      }
    }
    wx.navigateTo({
      url: '../productDetails/productDetails?sku_code=' + sku_code
    })


    // that.outSelect();
    // let timer = setTimeout(function(){
    //   that.setData({
    //     buyGoods: goodsInfo,
    //     numbers: 1,
    //     wineDome: false
    //   })
    //   clearTimeout(timer)
    // },500)
  },
  goToHops:function(){
    wx.navigateTo({
      url: '../hops/hops'
    })
  },
  closeBuy: function () {
    this.setData({
      wineDome: true
    })
  },

  addNum: function () {
    var num = this.data.numbers;
    num++;
    this.setData({
      numbers: num
    })
  },
  minusNum: function () {
    var num = this.data.numbers;
    if (num > 1) {
      num--;
      this.setData({
        numbers: num
      })
    }
  },

  // 支付订单
  payOrder: function () {
    var that = this;
    var buyGoods = that.data.buyGoods;
    var params = new Object()
    params.record = [];
    var list = [];
    var box = {};
    box.sku_code = buyGoods.sku_code
    box.num = that.data.numbers
    list.push(box);
    params.record = JSON.stringify(list)
    params.buy_type = 1;
    util.showLoading("加载中");
    api.POST({
      params: params,
      url: app.globalData.base_url + 'order/submit',
      success: function (res) {
        util.hiddenLoading();
        if (util.isEmpty(res.data.code)) {
          wx.removeStorageSync('shopId')
          that.wxPayOrder(res.data.data.result.oid, res.data.data.result.type);
        } else if (res.data.code == "2499") {
          util.showError("库存不足");
        } else {
          util.showError(res.data.message);
        }
      },
      fail: function (fail) {
        util.showError("登录失败，请检查网络");
      }
    })
  },
  //支付接口
  wxPayOrder: function (oid, types) {
    var params = new Object()
    var that = this;
    params.oid = oid;
    api.POST({
      params: { oid: oid },
      url: app.globalData.base_url + 'payment/getWechatInfo',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          var preData = res.data.data.payinfo;
          wx.requestPayment({
            timeStamp: preData.timeStamp,
            nonceStr: preData.nonceStr,
            package: preData.package,
            signType: preData.signType,
            paySign: preData.paySign,
            success: function (res) {
              that.wineList(); //获取酒柜列表
              that.closeBuy();
            },
            fail: function (error) {
              util.showError("支付失败");
              wx.removeStorageSync('orderData');
            }
          })
        } else {
          util.showError(res.data.message);
        }
      },
      fail: function (fail) {
        util.showError("登录失败，请检查网络");
      }
    })
  },

  //配送按钮
  peisong: function (e) {
    wx.navigateTo({
      url: '../wineDistribution/wineDistribution'
    })
  },
  //取货按钮
  pickUp: function (e) {
    // wx.navigateTo({
    //   url: '../wineSelfGet/wineSelfGet?sku_code=' + this.data.goodsInfo.sku_code
    // })
    wx.navigateTo({
      url: '../wineSelfGet/wineSelfGet'
    })
  },
  //商家二维码取货
  codePickUp: function () {
    // if (this.data.codeCol){
    //   wx.navigateTo({
    //     url: '../codePickUp/codePickUp?flag=' + true
    //   })
    // }else{
    //   wx.navigateTo({
    //     url: '../codePickUp/codePickUp?flag='+false
    //   })
    // }
    wx.navigateTo({
      url: '../wineSelfGet/wineSelfGet'
    })
  },
  footprint:function(){
    wx.navigateTo({
      url: '../footprint/footprint'
    })
  },
  //赠送按钮
  giving: function (e) {
    wx.navigateTo({
      url: '../giving/giving?sku_code=' + this.data.goodsInfo.sku_code
    })
  },
  //拆分数组
  split_array: function (arr, len, types) {
    var a_len = arr.length;
    var box_arr = [];
    var new_arr = [];
    var num =0;
    for (var i = 0; i < a_len; i ++) {
      if (types == "winBox") {
        if (arr[i].id) {
          num++;
        }
      }
    }
    for (var i = 0; i < a_len; i += len) {
      box_arr.push(arr.slice(i, i + len));
    }
    if (box_arr.length < 4) {
      var arr_new = [];
      for (var n = box_arr.length; n < 4; n++) {
        box_arr.push(arr_new);
      }
    }
    if (types=="winBox"){

      if (num > 0) {
        this.setData({
          codeCol: true
        })
      } else {
        this.setData({
          codeCol: false
        })
      }

      this.setData({
        newProductData: box_arr
      })
    } else if (types = "hops"){
      this.setData({
        newHopsData: box_arr
      })
    }
  },
  //  合成酒花
  marrying:function(){
    var that = this;

    wx.showModal({
      title: '提示',
      content: '是否"合成"该酒花',
      success: function (res) {
        if (res.confirm) {
          var id = that.data.goodsInfoHops.id;
          var sku_code = that.data.goodsInfoHops.sku_code;
          api.POST({
            params: { id: id },
            url: app.globalData.base_url + 'hops/synthesis',
            success: function (res) {
              if (util.isEmpty(res.data.code)) {
                that.flyOutHops();
                that.fadeInMarry();
                that.setData({
                  marry_code: sku_code,
                  marryImg: res.data.data.result.img,
                  marryName: res.data.data.result.ganme,
                  page: 1
                })
                that.wineList();
                that.hopsList();
              } else {
                util.showError(res.data.message);
              }
            },
            fail: function (fail) {
              util.showError("登录失败，请检查网络");
            }
          })
        }
      }
    })
  },

  // 分享事件
  onShareAppMessage: function (res) {
    var that = this;
    var linkCode = this.data.linkCode;
    var name = that.data.goodsInfoHops.hops_name
    var userinfo = app.globalData.accountInfo;
    var uid = userinfo.uid;
    var img = that.data.goodsInfoHops.share_img;
    if (res.from === 'button') {
      // 来自页面内转发按钮
      return {
        title: '好友"' + userinfo.nickname + '"送您"' + name + '"酒花',
        path: '/pages/giftShare/giftShare?uid=' + uid + '&show_type=4&linkCode=' + linkCode+'&shareType=1',
        imageUrl: img,
        success: function (res) {
          that.sharehops();
        },
        fail: function (res) {
          // 转发失败
        }
      }
    }
  },
// 酒花分享回调
  sharehops:function(){
    var that = this;
    var linkCode = this.data.linkCode;
    api.POST({
      params: { linkCode: linkCode },
      url: app.globalData.base_url + 'hops/successSmg',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          that.outSelectHops();
          that.setData({
            page: 1
          })
          that.wineList();
          that.hopsList();
          // setTimeout(function(){
          //   util.showError("分享成功");
          // },500)
        } else {
          that.outSelectHops();
          util.showError(res.data.message);
        }
      },
      fail: function (fail) {
        util.showError("登录失败，请检查网络");
      }
    })
  }
})